package stvd.sign;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.ParseException;

import org.springframework.security.crypto.codec.Base64;
import org.stvd.core.util.DateUtil;

public class SignEncode { 
    
    /**
     * 用私钥，对要加密的信息进行加密
     * @param priKeyText 私钥
     * @param plainText  被加密的明文
     * @return 返回加密后的密文
     */
	public static byte[] sign(byte[] priKeyText, String plainText) { 
		try { 
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(priKeyText)); 
			KeyFactory keyf = KeyFactory.getInstance("RSA"); 
			PrivateKey prikey = keyf.generatePrivate(priPKCS8); 
			// 用私钥对信息生成数字签名 
			Signature signet = java.security.Signature.getInstance("MD5withRSA"); 
			signet.initSign(prikey); 
			signet.update(plainText.getBytes()); 
			return Base64.encode(signet.sign()); 
		} catch (java.lang.Exception e) { 
			e.printStackTrace(); 
		} 
		return null; 
	}
	
	public static void main(String[] args) {
		SignProvider signProvider = new SignProvider();
		
		try {
			boolean bExpires = DateUtil.beforDate2(DateUtil.getSystemDateOfY2D(),signProvider.getExpiresDate());
			System.out.println("SysDate = " + DateUtil.getSystemDateOfY2D()) ;
			System.out.println("ExpiresDate = " + signProvider.getExpiresDate()) ;
			System.out.println("bExpires = " + bExpires );
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		KeyGenerater keyGenerater = new KeyGenerater() ;
//		keyGenerater.setSeed(signProvider.getSerialNum()+signProvider.getExpiresDate()+signProvider.getUserName());
		keyGenerater.generater();
		//用私钥进行加密，将licenseText加密后，得到signdText
		byte[] signdText = SignEncode.sign(keyGenerater.getPriKey(),signProvider.getLicenseText());
		//用公钥进行签名校验，与加密的signdText进行校验
		boolean signdResult = SignProvider.verify(keyGenerater.getPubKey(), signProvider.getLicenseText(), signdText);
		
		System.out.println("licenseText = "+signProvider.getLicenseText());
		System.out.println("licenseText = "+new String(Base64.decode(signProvider.getLicenseText().getBytes())));
		System.out.println("signdText = " + new String(signdText));
		System.out.println("signdResult = " + signdResult);
		
		System.out.println("Test Result is :" + SignProvider.verify());
	}
} 